package userdao

import (
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/base"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/userdata"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
)

const sqlSaveOrUpdate = `
INSERT INTO t_user
( 
	user_name, 
    password, 
    hero_avatar, 
 	cur_hp,
 	create_time, 
 	last_login_time 
) 
VALUE 
( 
    ?, ?, ?, ?, ? ,?
)
ON DUPLICATE KEY UPDATE cur_hp = values(cur_hp) , last_login_time = values(last_login_time);
`

// SaveOrUpdate 保存或更新用户
func SaveOrUpdate(user *userdata.User) {
	if nil == user {
		return
	}

	stmt, err := base.MysqlDB.Prepare(sqlSaveOrUpdate)

	if nil != err {
		log.Error("%+v", err)
		return
	}

	result, err := stmt.Exec(
		user.UserName,
		user.Password,
		user.HeroAvatar,
		user.CurHp,
		user.CreateTime,
		user.LastLoginTime,
	)

	if nil != err {
		log.Error("%+v", err)
	}

	rowId, err := result.LastInsertId()

	if nil != err {
		log.Error("%+v", err)
	}

	user.UserId = uint32(rowId)
}
